package vn.com.demand.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.xml.transform.TransformerException;

import vn.com.demand.lux.model.UpdateIssuingExpenseBean;

import com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl;
import com.wutka.jox.JOXBeanInputStream;
import com.wutka.jox.JOXBeanOutputStream;

public class XMLUtils {

	/*
	 * Transform xml file with mapping xsl file to xml result
	 * 
	 * @param xmlRawFile .The original xml file @param xslMappingFile .The xsl
	 * mapping file
	 * 
	 * @return the xml result file at resultFileLocation
	 * 
	 */

	public static File transform(String xmlRawFilePath,
			String xslMappingFilePath, File resultFile)
			throws TransformerException, IOException {
		javax.xml.transform.TransformerFactory tFactory = javax.xml.transform.TransformerFactory
				.newInstance();
		javax.xml.transform.Transformer transformer = tFactory
				.newTransformer(new javax.xml.transform.stream.StreamSource(
						new File(xslMappingFilePath)));
		// Cast the Transformer object to TransformerImpl.
		if (transformer instanceof TransformerImpl) {
			FileOutputStream result = new FileOutputStream(resultFile);
			transformer.transform(new javax.xml.transform.stream.StreamSource(
					new FileInputStream(new File(xmlRawFilePath))),
					new javax.xml.transform.stream.StreamResult(result));
			result.flush();
			result.close();
			return resultFile;
		}
		return null;
	}

	public static void writeXMLFile(Object obj, String path) throws Exception {
		try {
			FileOutputStream fileOut = new FileOutputStream(path);
			
			JOXBeanOutputStream joxOut = new JOXBeanOutputStream(fileOut);
			
			joxOut.writeObject("bean", obj);
			joxOut.close();
		} catch (Exception exc) {
			throw exc;
		}
	}

	public static Object readXMLFile(Class clazz, String path) throws Exception {
		try {
			FileInputStream in = new FileInputStream(path);

			JOXBeanInputStream joxIn = new JOXBeanInputStream(in);

			Object bean = (Object)joxIn.readObject(clazz);
			return bean;
		} catch (Exception exc) {
			throw exc;
		}
	}
	
	public static void main(String[] args) {
		
		UpdateIssuingExpenseBean u = new UpdateIssuingExpenseBean();
		u.setJournalCode("11111");
		u.setLedgerCode("22222");
		u.setLedgerName("Huynh Tan Tai");
		try {
			writeXMLFile(u, "bean.xml");
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		//---------------------
		
		UpdateIssuingExpenseBean u2;
		try {
			u2 = (UpdateIssuingExpenseBean)readXMLFile(UpdateIssuingExpenseBean.class, "bean.xml");
			System.out.println("===" + u2.getLedgerCode());
			System.out.println("===" + u2.getLedgerName());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
